﻿using System;
using System.Linq;
using System.Data.Entity;
using GBlog.Core.Service;
using System.Linq.Expressions;

namespace GBlog.Core.Data.Default
{
    public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
    {
        private IDbContext Context;
        private IConfigService Config;

        private IDbSet<TEntity> Entities
        {
            get { return this.Context.Set<TEntity>(); }
        }

        public Repository(IDbContext context, IConfigService config)
        {
            this.Context = context;
            this.Config = config;
        }

        public IQueryable<TEntity> GetAll()
        {
            return Entities.AsQueryable();
        }

        public TEntity GetByID(object id)
        {
            return Entities.Find(id);
        }

        public void Insert(TEntity entity)
        {
            Entities.Add(entity);
            this.Context.SaveChanges();
        }

        public void Update(TEntity entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            this.Context.SaveChanges();
        }

        public void Delete(TEntity entity)
        {
            Entities.Remove(entity);
            this.Context.SaveChanges();
        }

        public void Delete(object ID)
        {
            Entities.Remove(Entities.Find(ID));
            this.Context.SaveChanges();
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (this.Context != null)
                {
                    this.Context.Dispose();
                    this.Context = null;
                }
            }
        }


        public int Count()
        {
            return Entities.Count();
        }

        public int Count(Expression<Func<TEntity, bool>> Expression)
        {
            return Entities.Count(Expression);
        }
    }
}